package com.dong.servlet;

import org.springframework.scheduling.annotation.EnableAsync;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <h1>servelt 3.0 异步处理</h1>
 *
 * @author : dzj
 * @create: 2020-05-05 15:02
 */

    //支持异步
@WebServlet(value = "async",asyncSupported = true)
public class HelloAsyncServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //开启异步
        AsyncContext asyncContext = req.startAsync();
        //开hi异步处理
        asyncContext.start(()-> {sayHello();
        asyncContext.complete();
            AsyncContext asyncContext1 = req.getAsyncContext();
            try {
                asyncContext1.getResponse().getWriter().write("hello async");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        sayHello();
    }
    public void sayHello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello");
    }
}
